package edu.cmu.cs.webapp.ioms.actions.user;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.UserDAOImpl;
import edu.cmu.cs.webapp.ioms.logging.Alerts;
import edu.cmu.cs.webapp.ioms.models.User;
import edu.cmu.cs.webapp.ioms.views.UsersListView;

public class DeleteUserViewAction implements IViewActionDelegate {
	private User _model;
	private UsersListView _view;

	@Override
	public void init(IViewPart view) {
		this._view = (UsersListView) view;

	}

	@Override
	public void run(IAction action) {
		if (this._model != null) {

			if (MessageDialog.openConfirm(this._view.getViewSite().getShell(),
					"Delete Confirmation",
					"Are you sure you want to delete this user record?")) {
				try {
					new UserDAOImpl().deleteUser(_model);
				} catch (DataAccessException e) {
					Alerts.getInstance().detailError("Data Access Error",
							e.getLocalizedMessage(), e);
				}
			}

			this._view.refreshUsersView();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof User) {
				this._model = (User) obj;
			}
		}
	}
}
